<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    top="4%"
    width="75%"
    :before-close="close"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-scrollbar max-height="61vh" v-loading="loading">
      <div class="mr-4">
        <MatterInfo ref="matterInfo" />
        <ProcessPane ref="processPane" />
        <el-form
          v-if="isApprove === EDetailType.APPROVE"
          ref="formRef"
          label-width="110px"
          :model="formData"
          :rules="rules"
        >
          <el-form-item label="审核意见" prop="processOpinion">
            <el-input
              v-model="formData.processOpinion"
              type="textarea"
              :autosize="{ minRows: 5 }"
            />
          </el-form-item>
          <el-form-item
            v-if="showApproveUser"
            label="下一节点审核人"
            prop="nextProcessUserId"
          >
            <SelectApproveUser
              v-model="formData.nextProcessUserId"
              :type="ESelectApproveUserType.DEAL"
              :feedbackId="rowData.feedbackId"
            />
          </el-form-item>
          <el-form-item v-if="showRecomment" label="办理评价" prop="appraise">
            <el-select v-model="formData.appraise">
              <el-option
                v-for="item in appraiseList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">
          {{ isApprove === EDetailType.APPROVE ? '取消' : '关闭' }}
        </el-button>
        <template v-if="isApprove === EDetailType.APPROVE">
          <el-button type="danger" @click="submit(2)">不通过</el-button>
          <el-button type="primary" @click="submit(1)">通过</el-button>
        </template>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { computed, nextTick, reactive, ref, useTemplateRef } from 'vue'
import MatterInfo from '@/components/showInfo/MatterInfo.vue'
import {
  agreeFeedback,
  disagreeFeedback,
  getApproveFormInfo,
} from '@/api/mission/review'
import ProcessPane from '@/components/showInfo/process/ProcessPane.vue'
import { ElMessageBox, FormInstance, FormRules } from 'element-plus'
import { EDetailType } from '@/views/application/typings'
import { Message } from '@/hooks/message'
import SelectApproveUser from '@/components/user/SelectApproveUser.vue'
import { ESelectApproveUserType } from '@/api/sys/userManage'
import {
  getLastApproveItem,
  isLastApprovePerson,
} from '@/views/application/utils'

const appraiseList = [
  {
    label: '好',
    value: 1,
  },
  {
    label: '较好',
    value: 2,
  },
  {
    label: '一般',
    value: 3,
  },
  {
    label: '较差',
    value: 4,
  },
]

const emit = defineEmits(['update'])
const matterInfo = useTemplateRef<InstanceType<typeof MatterInfo>>('matterInfo')
const processPane =
  useTemplateRef<InstanceType<typeof ProcessPane>>('processPane')
const formRef = useTemplateRef<FormInstance>('formRef')

const dialogVisible = ref(false)
const loading = ref(false)
const submitType = ref(0)
const result = ref(null)
const rowData = reactive({
  feedbackId: null,
  matterId: null,
  id: null,
})
const formData = reactive({
  processOpinion: null,
  nextProcessUserId: null,
  appraise: null,
})

const rules = ref<FormRules<typeof formData>>({
  processOpinion: [
    {
      required: true,
      message: '请输入审核意见',
      trigger: 'blur',
    },
  ],
  nextProcessUserId: [
    {
      validator: validatorUserId,
    },
  ],
  appraise: [
    {
      validator: validatorAppraise,
    },
  ],
})

const showApproveUser = computed(() => {
  if (!result.value) return false
  return !isLastApprovePerson(result.value.processInfoList)
})

const showRecomment = computed(() => {
  if (!result.value) return false
  const lastNode = getLastApproveItem(result.value.processInfoList)
  if (lastNode) {
    const { isLastNode, type } = lastNode || {}
    if (isLastNode) {
      // 牵头单位单位
      if (type === 1) {
        return true
      }
    }
  }
  return false
})

const lastProcessNode = computed(() => {
  if (!result.value) {
    return {}
  } else {
    return result.value.processInfoList[result.value.processInfoList.length - 1]
  }
})

function validatorUserId(rule: any, value: any, callback: any) {
  if (submitType.value === 1 && !value && showApproveUser.value) {
    callback(new Error('审核通过必须选择下一步的审核人'))
  } else {
    callback()
  }
}

function validatorAppraise(rule: any, value: any, callback: any) {
  if (submitType.value === 1 && !value && showRecomment.value) {
    callback(new Error('审批通过必须选择办理评价'))
  } else {
    callback()
  }
}

defineExpose({ show })

const isApprove = ref(EDetailType.APPROVE)

const title = computed(() => {
  return isApprove.value === EDetailType.APPROVE
    ? '审核办理结果'
    : '办理结果详情'
})

function show(row: any, approve = EDetailType.APPROVE) {
  dialogVisible.value = true
  isApprove.value = approve
  nextTick(async () => {
    Object.assign(rowData, {
      matterId: row.matterId,
      id: row.id,
      feedbackId: row.feedbackId,
    })
    loading.value = true
    await initData()
    loading.value = false
  })
}

async function initData() {
  const { data } = await getApproveFormInfo(rowData.feedbackId)
  if (data.status === 200) {
    result.value = data.data
    await matterInfo.value.setData(data.data)
    processPane.value.setData([data.data])
  }
}

function close() {
  dialogVisible.value = false
  loading.value = false
  submitType.value = 0
  result.value = null
  isApprove.value = EDetailType.APPROVE
  formRef.value.resetFields()
  Object.assign(rowData, {
    matterId: null,
    id: null,
    feedbackId: null,
  })

  Object.assign(formData, {
    processOpinion: null,
    nextProcessUserId: null,
    appraise: null,
  })
  emit('update')
}

function submit(type: number) {
  submitType.value = type
  formRef.value.validate(async (bool: boolean) => {
    if (!bool) {
      return
    }

    const postData = {
      processId: lastProcessNode.value.id,
      feedbackId: rowData.feedbackId,
      matterId: rowData.matterId,
      deadlineId: result.value.deadlineId,
      processResult: type,
      processNode: lastProcessNode.value.processNode,
      processOpinion: formData.processOpinion,
      nextProcessUserId: formData.nextProcessUserId,
      appraise: formData.appraise,
    }

    if (type === 1) {
      ElMessageBox.confirm('确定审核通过吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          loading.value = true
          const { data } = await agreeFeedback(postData)
          if (data.status === 200) {
            Message({
              message: data.message,
              type: 'success',
            })
            loading.value = false
            emit('update')
            close()
          }
        })
        .catch(() => {})
    } else if (type === 2) {
      ElMessageBox.confirm('确定不通过 吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          loading.value = true
          const { data } = await disagreeFeedback(postData)
          if (data.status === 200) {
            Message({
              message: data.message,
              type: 'success',
            })
            loading.value = false
            emit('update')
            close()
          }
        })
        .catch(() => {})
    }
  })
}
</script>

<style scoped lang="scss">
:deep(.el-step__description) {
  white-space: pre-wrap;
}
</style>
